package site.ycsyxt.util;

import javax.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * http操作相关工具类
 *
 * @author ycs(15241496739 @ 163.com)
 * @date 2022/1/3
 **/
public class HttpUtils {
    /**
     * 小项目使用默认配置即可
     * <p>
     * 大项目需要专门配置链接数，链接池，超时重试...，详见：https://blog.csdn.net/w372426096/article/details/82713315
     */
    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 避免请求被当成网络攻击
     */
    private static final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
            "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36";

    // IP地址查询
    public static final String IP_URL = "https://searchplugin.csdn.net/api/v1/ip/get";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    /**
     * 文件下载
     *
     * @param url
     * @return
     */
    public static byte[] download(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", userAgent);
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            return EntityUtils.toByteArray(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败！url = " + url + "\n" + e);
        }
    }

    /**
     * 文件上传
     *
     * @param url
     * @param file
     * @return
     */
    public static String upload(String url, byte[] file, String fileName) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", userAgent);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        ByteArrayBody byteArrayBody = new ByteArrayBody(file, fileName);
        builder.addPart("file", byteArrayBody);
        httpPost.setEntity(builder.build());
        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败！url = " + url + "\n" + e);
        }
    }

    /**
     * 发送HttpGet请求
     *
     * @param url
     * @param params 请求参数, 为null表示无参
     * @return JSON字符串
     */
    public static String sendGet(String url, Map<String, Object> params) {
        url = appendParams(url, params);
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", userAgent);
        httpGet.setHeader("Accept-Charset", Consts.UTF_8.name());
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException("发送HttpGet请求失败！url = " + url + "\n" + e);
        }
    }

    /**
     * 添加get请求参数
     *
     * @param url
     * @param params
     * @return
     */
    private static String appendParams(String url, Map<String, Object> params) {
        if (null != params && params.size() > 0) {
            StringBuffer param = new StringBuffer();
            int i = 0;
            for (String key : params.keySet()) {
                if (i == 0) {
                    param.append("?");
                } else {
                    param.append("&");
                }
                param.append(key).append("=").append(params.get(key));
                i++;
            }
            url += param;
        }
        return url;
    }

    /**
     * 发送HttpPost请求
     *
     * @param url
     * @param jsonStr 请求JSON字符串参数, 为null表示无参
     * @return JSON字符串
     */
    public static String sendPost(String url, String jsonStr) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", userAgent);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (null != jsonStr) {
            StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
            httpPost.setEntity(entity);
        }
        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException("发送HttpPost请求失败！url = " + url + "\n" + e);
        }
    }

    /**
     * 获取用户真实IP地址
     * <p>
     * 不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址
     *
     * @param request
     * @return
     */
    public static String getRealClientIp(HttpServletRequest request) {
        //如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }
        //apache http做代理时一般会加上Proxy-Client-IP请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        //apache http做代理时，weblogic插件加上WL-Proxy-Client-IP。
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        //部分代理服务器加的请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        //分代理服务器加的请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //nginx代理一般会加上此请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        //当不使用代理获取的ip
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String hostAddress = "127.0.0.1";
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException("获取用户ip失败！");
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? hostAddress : ip;
    }

    public static String getRealAddressByIP(String ip) {
        if ("127.0.0.1".equals(ip)) {
            return "内网IP";
        }
        try {
            HashMap<String, Object> params = Maps.newHashMap();
            params.put("ip", ip);
            String rspStr = sendGet(IP_URL, params);
            if (StringUtils.isBlank(rspStr)) {
                return UNKNOWN;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String data = obj.getString("data");
            JSONObject address = JSONObject.parseObject(data);
            return (String) address.get("address");
        } catch (Exception e) {
            throw new RuntimeException("获取地理位置失败！ip = " + ip);
        }
    }
}

